package com.wenhui.nzapp.ui.activity.dinnerqr;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.gzwh.weblib.bean.NzDinnerQrcode;
import com.gzwh.weblib.bean.NzDinnerRegion;
import com.gzwh.weblib.bean.Result;
import com.gzwh.weblib.utils.MyObserver;
import com.gzwh.weblib.utils.RequestUtils;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.hmsscankit.WriterException;
import com.huawei.hms.ml.scan.HmsBuildBitmapOption;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.wenhui.nzapp.R;
import com.wenhui.nzapp.ui.adapter.DinnerQrAreAdapter;
import com.wenhuitec.sysui.TitleBuilder;
import com.wenhuitec.sysui.dialog.ApRadioBoxDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class DinnerQrTableEditActivity extends AppCompatActivity {
    private Context mContext;

    private TextView areSelectTv;
    private int REQUEST_CODE_SCAN_ONE = 1111;

    private ImageView qrCodeImg;
    private boolean updateOrSave = false;

    private String qrId;

    private EditText tableNameEd;

    private String url = "https://qr.wenhuitec.com/miniApp/Zong/dinner";
    private NzDinnerQrcode dinnerQrcode;

    public static void startAct(Context context, NzDinnerQrcode nzDinnerQrcode) {
        Intent intent = new Intent(context, DinnerQrTableEditActivity.class);
        intent.putExtra("data", JSONObject.toJSONString(nzDinnerQrcode));
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dinnerqr_tableedit);
        mContext = this;
        tableNameEd = findViewById(R.id.tableNameEd);
        areSelectTv = findViewById(R.id.areSelectTv);
        qrCodeImg = findViewById(R.id.qrCodeImg);
        try {
            String data = this.getIntent().getExtras().getString("data");
            dinnerQrcode = JSONObject.parseObject(data, NzDinnerQrcode.class);
            updateOrSave = true;
            tableNameEd.setText(dinnerQrcode.getTableName());
            qrId = dinnerQrcode.getId();
//            deleteAre.setVisibility(View.VISIBLE);

            showQr(url + "?code=" + dinnerQrcode.getCode());
        } catch (Exception e) {
//            e.printStackTrace();
        }
        new TitleBuilder(this)
                .setTitleText(updateOrSave ? "编辑桌台" : "新增桌台")
//                .setLeftIco(R.drawable.yp)
                .setLeftIcoListening((view) -> finish());
        areSelectTv = findViewById(R.id.areSelectTv);

        areSelectTv.setOnClickListener(view -> {
            List<Map<String, String>> reMap = new ArrayList<>();
            for (NzDinnerRegion goo : nzDinnerRegionList) {
                Map<String, String> map = new HashMap<>();
                map.put("name", goo.getName());
                map.put("id", goo.getId());
                reMap.add(map);
            }
            ApRadioBoxDialog apRadioBoxDialog = new ApRadioBoxDialog();
            apRadioBoxDialog.showApRadioBoxDialog(mContext, reMap);
            apRadioBoxDialog.setOnUserClick((map -> {
//                menuFoodModel.setMenuCateId(map.get("id"));
                areSelectTv.setText(map.get("name"));
            }));
        });

        findViewById(R.id.sanCodeBut).setOnClickListener(view -> {
            HmsScanAnalyzerOptions options = new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE, HmsScan.DATAMATRIX_SCAN_TYPE).setViewType(1).setErrorCheck(true).create();
            ScanUtil.startScan(this, REQUEST_CODE_SCAN_ONE, options);
        });
        findViewById(R.id.makeCodeBut).setOnClickListener(view -> {
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            showQr(uuid);
        });
    }

    private void showQr(String code) {
        int type = 3;     // HmsScan.QRCODE_SCAN_TYPE 的值为1
        int width = 300;
        int height = 300;
        HmsBuildBitmapOption options = new HmsBuildBitmapOption.Creator().create();

        try {

            Bitmap qrBitmap = ScanUtil.buildBitmap(code, type, width, height, options);
            qrCodeImg.setImageBitmap(qrBitmap);  // 将二维码显示在ImageView中
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    private List<NzDinnerRegion> nzDinnerRegionList;

    @Override
    public void onResume() {
        super.onResume();
        RequestUtils.getAreList(mContext, new MyObserver<List<NzDinnerRegion>>(mContext, false) {
            @Override
            public void onSuccess(Result<List<NzDinnerRegion>> result) {
                System.out.println(result.toString());
                nzDinnerRegionList = result.getResult();
                if (dinnerQrcode != null) {
                    NzDinnerRegion nzDinnerRegion = nzDinnerRegionList.stream().filter(nzDinnerRegion1 -> nzDinnerRegion1.getId().equals(dinnerQrcode.getRegionId()))
                            .findFirst().orElse(null);
                    if (nzDinnerRegion != null) {
                        areSelectTv.setText(nzDinnerRegion.getName());
                    }
                }


            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            // 导入图片扫描返回结果
            int errorCode = data.getIntExtra(ScanUtil.RESULT_CODE, ScanUtil.SUCCESS);
            if (errorCode == ScanUtil.SUCCESS) {
                Object obj = data.getParcelableExtra(ScanUtil.RESULT);
                if (obj != null) {
                    // 展示扫码结果
                    Toast.makeText(mContext, obj.toString(), Toast.LENGTH_LONG).show();
                }
            }
            if (errorCode == ScanUtil.ERROR_NO_READ_PERMISSION) {
                // 无文件权限，请求文件权限

            }
        }
    }
}
